package com.copote.util;

import org.apache.commons.codec.binary.Base64;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Random;


/**
 * @author adminstrator
 */
public class AesUtil {
    private static BASE64Encoder base64Encoder;
    private static BASE64Decoder base64Decoder;
    private static IvParameterSpec iv;
    private static Integer length = 16;
    private static String char_str = "abcdefghijklmnop";
    /**
     * "算法/模式/补码方式
     */
    private static String CipherType = "AES/CBC/PKCS5Padding";
    private static String sKey;

    static {
        base64Decoder = new BASE64Decoder();
        base64Encoder = new BASE64Encoder();
        // 使用CBC模式，需要一个向量iv，可增加加密算法的强度
        iv = new IvParameterSpec("0102030405060708".getBytes());
    }
    public static String initKey(){
        Random random=new Random();
        StringBuffer sb=new StringBuffer();
        for(int i=0;i<length;i++){
            int number=random.nextInt(length);
            sb.append(char_str.charAt(number));
        }
        sKey = sb.toString();
        return sKey;
    }
    public static String getsKey() {
        return sKey;
    }

    public static void setsKey(String sKey) {
        AesUtil.sKey = sKey;
    }

    /**
     * 加密
     * @param sSrc
     * @return
     */
    public synchronized static String encrypt(String sSrc) {
        try {
            // 判断Key是否为16位
            if (length != sKey.length()) {
                System.out.print("Key长度不是16位");
                return null;
            }
            byte[] raw = sKey.getBytes("UTF-8");
            Cipher cipher = Cipher.getInstance(CipherType);
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
            byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));
            String encode = Base64.encodeBase64String(encrypted);
            return encode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (sKey == null) {
            System.out.print("Key为空null");
            return null;
        }
        return null;

    }

    /**
     * 解密
     * @param sSrc
     * @return
     */
    public synchronized static String decrypt(String sSrc) {
        try {
            // 判断Key是否正确
            if (sKey == null) {
                System.out.print("Key为空null");
                return null;
            }
            // 判断Key是否为16位
            if (sKey.length() != length) {
                System.out.print("Key长度不是16位");
                return null;
            }
            byte[] raw = sKey.getBytes("UTF-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance(CipherType);

            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            // 先用base64解密
            byte[] encrypted1 = Base64.decodeBase64(sSrc);
            try {
                byte[] original = cipher.doFinal(encrypted1);

                String dencode =  new String(original, "utf-8");
                return dencode;
            } catch (Exception e) {
                System.out.println(e.toString());
                return null;
            }
        } catch (Exception ex) {
            return null;
        }
    }

    /**
     * 将二进制转换成16进制
     *
     * @param buf
     * @return
     */
    public static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    /**
     * 将16进制转换为二进制
     *
     * @param hexStr
     * @return
     */
    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1){
            return null;
        }

        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

}
